package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtPractice implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler){
        System.out.println("当前的线程id"+Thread.currentThread().getId());
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        try {
            String token = request.getHeader(jwtProperties.getUserTokenName());
            log.info("开始校验:{}",token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            log.info("当前员工ID：{}",empId);
            BaseContext.setCurrentId(empId);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }


    }



}
